<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../js/vue.js"></script>
</head>
<body>
     <div id="app">
         {{message}}
     </div>
</body>
<script>
    const app = new Vue({
        el:"#app",
        data:{
            message:"aaa"
        }
    });

    /*当app.message修改数据，vue内部是如何监听message数据的变化的？
        Object.defineProperty -> 监听对象属性的改变
    */
    const obj = {
        message:"aaa"
    };

    Object.keys(obj).forEach(key=>{
        let value = obj[key];

        Object.defineProperty(obj,key,{
            set(newValue){
                console.log("监听[" + key + "]的改变");
                //通过解析html代码，获取那些人有用属性
                value = newValue;
            },
            get(){
                console.log("获取[" + key + "]的值");
                //a:get -> update
                //b:get -> update
                return value;
            }
        });
    });

     /*当数据发生改变，vue是如何知道要通知那些地方的界面发生刷新？
        发布订阅者模式
     */
     class Dep{
         constructor(){
             this.subs = [];
         }

         addSub(watcher){
            this.subs.push(watcher);
         }

         notify(){
             this.subs.forEach(item=>{
                 item.update();
             })
         }
     }

     class Watcher{
         constructor(name){
             this.name = name;
         }

         update(){
             console.log(this.name+"发生了变化");
         }
     }

     const dep = new Dep();
     dep.addSub(new Watcher("张三"));
     dep.addSub(new Watcher("李四"));
     dep.addSub(new Watcher("王五"));

     dep.notify();
</script>
</html>


